<template>
	<view class="container">
		<TopNav title="详情" :theme="'white'"></TopNav>
		<view class="main">
			<view class="header shrink-0">
				<view class="flex align-center full-width">
					<image src="/static/images/signup/time-1.png" class="width-20 height-20 m-r4" mode=""></image>
					<text class="text-bold line-height28 f-s17" style="color: #F9F9F9;">
						期望上门时间 {{formatArriveTime(detailData.appointment_arrive_time)}}
					</text>

				</view>
				<view class="m-t14 relative">
					<image src="/static/images/signup/map-bg.png" style="width: 100%;height: 160rpx;" mode=""></image>
					<view class="absolute p-lr12 p-t12" @click="handleOpenMapApp">
						<view class="flex align-center">
							<image src="/static/images/signup/location-2.png" class="width-24 height-24 m-r10" mode="">
							</image>
							<text class="text-bold f-s17 line-height20">{{detailData.address}}</text>
						</view>
						<view class="m-t12 flex">
							<view class="width-34">
							</view>
							<text
								class="text-gray f-s14 line-height16">{{detailData.province}}{{detailData.city}}{{detailData.district}}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="flex-1 overflow-hidden m-t12 main-content">
				<scroll-view scroll-y="true" class="full-height">
					<view class="bg-white radius p-12" v-if="detailData.publish_user_data">
						<view class="">
							<text class="text-bold f-s17 line-height22 m-r8 text-black">发布客户</text>
						</view>
						<view class="m-t10 flex justify-between align-center">
							<view class="flex align-center">
								<image :src="detailData.publish_user_data.avatar || '/static/logo.png'" class="bg-gray round width-28 height-28 m-r10"
									mode=""></image>
								<text class="m-r8 f-s14 line-height20">{{detailData.publish_user_data.nickname}}</text>
								<image src="/static/images/order/vip.png" v-if="detailData.publish_user_data.is_vip > 0" class="width-23 height-16"
									mode="" @click="$toast('VIP客户')"></image>
							</view>
						
						</view>
					</view>
					<view class="radius bg-white p-12 m-t10">
						<view class="flex align-center">
							<text class="text-bold f-s17 line-height22 m-r8 text-black">搭搭下单</text>
							<!-- <image src="/static/images/signup/vip.png" class="width-24 height-16" mode=""
								@click="handleClickVip" v-if="(detailData.publish_user_data && detailData.publish_user_data.is_vip) == 1"></image> -->
						</view>
						<view class="flex align-center justify-between m-t16">
							<view class="flex align-center">
								<image src="/static/images/signup/service.png" class="width-20 height-20 m-r10" mode="">
								</image>
								<text style="color: #585D66;" class="f-s14 f-w400 line-height20">服务项目</text>
							</view>
							<text class="f-s14 f-w400 line-height20">{{detailData.service_name}}</text>
						</view>
						<view class="flex align-center justify-between m-t16">
							<view class="flex align-center">
								<image src="/static/images/signup/user.png" class="width-20 height-20 m-r10" mode="">
								</image>
								<text style="color: #585D66;" class="f-s14 f-w400 line-height20">搭搭人数</text>
							</view>
							<text class="f-s14 f-w400 line-height20">{{detailData.technician_person_num}}人</text>
						</view>
						<view class="flex align-center justify-between m-t16">
							<view class="flex align-center">
								<image src="/static/images/signup/time-2.png" class="width-20 height-20 m-r10" mode="">
								</image>
								<text style="color: #585D66;" class="f-s14 f-w400 line-height20">搭搭时长</text>
							</view>
							<text class="f-s14 f-w400 line-height20">{{detailData.activity_duration}}小时</text>
						</view>
						<view class="full-width m-t16" style="height: 1px;background-color: #DDE0E6;"></view>
						<!-- <view class="text-right m-t15">
							<text class="text-gray m-r8 f-s14 line-height20">搭搭酬金</text>
							<text
								class="text-theme text-bold f-s14 line-height18 p-r2">￥{{detailData.service_price}}</text>
							<text class="text-black f-s12 line-height16">/人</text>
						</view> -->
					</view>
					<view class="radius bg-white p-12 m-t10">
						<view class="">
							<text class="text-bold f-s17 line-height22 text-black">备注标签</text>
						</view>
						<view class="tag" v-if="detailData.remark_tags">
							<view class="tag-item" v-for="tagItem in detailData.remark_tags.split(',')" :key="tagItem">
								<text>{{tagItem}}</text>
							</view>
						</view>
					</view>
					<view class="radius bg-white p-12 m-t10">
						<view class="">
							<text class="text-bold f-s17 line-height22 text-black">报名须知</text>
						</view>
						<view class="m-t10 line-height24 f-s14" style="color: #585D66;">
							<u-parse v-if="detailData.support_apply"
								:content="detailData.support_apply.support_apply"></u-parse>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>

		<view class="flex justify-center fixed-bottom bg-white">

			<view class="self-btn flex flex-direction" style="height: 96rpx;" hover-class="pressed"
				v-if="detailData.apply_status == 0" @click="handleSignup">
				<text class="f-s16 line-height22 f-w500">立即报名</text>
				<view class="f-s11 line-height16 f-w500 flex justify-center">
					<text class="p-r2">{{detailData.apply_tech_count}}人已报名</text>
					<u-count-down :time="handleCutOffTime(detailData.end_apply_time)" format="HH:mm:ss"
						class="count-down" @finish="handleCutOffTimeFinish"></u-count-down>
					<text class="m-l2">后报名结束</text>
				</view>

			</view>

			<view class="self-btn flex flex-direction disabled" style="height: 96rpx;" hover-class="pressed"
				v-if="detailData.apply_status == 1 && !handleCancelTimeCheck(detailData.can_cancel_time)">
				<text class="f-s16 line-height22 f-w500">已报名</text>
				<view class="f-s11 line-height16 f-w500 flex justify-center">
					<u-count-down :time="handleCancelTime(detailData.can_cancel_time)" format="mm:ss" class="count-down"
						@finish="getDetail"></u-count-down>
					<text class="m-l2">后可取消报名</text>
				</view>
			</view>
			<view class="self-btn flex flex-direction cancel" style="height: 96rpx;" hover-class="pressed"
				@click="handleSignupCancel"
				v-if="detailData.apply_status == 1 && handleCancelTimeCheck(detailData.can_cancel_time)">
				<text class="f-s16 line-height22 f-w500">取消报名</text>
			</view>
			<view class="self-btn flex flex-direction disabled" style="height: 96rpx;" hover-class="pressed"
				v-if="detailData.apply_status == 2">
				<text class="f-s16 line-height22 f-w500">未选中</text>
			</view>
			<view class="self-btn flex flex-direction disabled" style="height: 96rpx;" hover-class="pressed"
				v-if="detailData.apply_status == -1">
				<text class="f-s16 line-height22 f-w500">已取消报名</text>
			</view>
			<view class="self-btn flex flex-direction disabled" style="height: 96rpx;" hover-class="pressed"
				v-if="detailData.apply_status == -2">
				<text class="f-s16 line-height22 f-w500">已取消</text>
			</view>
			<view class="self-btn flex flex-direction disabled" style="height: 96rpx;" hover-class="pressed"
				v-if="detailData.apply_status == 5">
				<text class="f-s16 line-height22 f-w500">已过期</text>
				<text style="font-size: 22rpx;" class="line-height16 f-w500">报名已结束</text>
			</view>
			<view class="self-btn flex flex-direction disabled" style="height: 96rpx;" hover-class="pressed"
				v-if="detailData.apply_status == 4">
				<text class="f-s16 line-height22 f-w500">已合作</text>
			</view>
			<view class="self-btn flex flex-direction disabled" style="height: 96rpx;" hover-class="pressed"
				v-if="detailData.apply_status == 3">
				<text class="f-s16 line-height22 f-w500">已选中</text>
			</view>
		</view>
		<Modal :show.sync="modalShow" content="你确认要取消本次项目的报名吗？" @confirm="handleConfrimeCancelSignup"></Modal>
		<Toast></Toast>
		<l-drag @btnClick='handleHelp'
			:boundary="{top: 200,left: 30,bottom: 240,right: 30}" :initLocation="{left: 620, top: 600 }">
			<view class="help-container">
				<text v-if="onlineConf.onlineStep == 2">{{formatSecondsToMinutesSeconds(onlineConf.tipsTime)}}</text>
				<text v-else>紧急\n救助</text>
			</view>
		</l-drag>
		<u-popup :show="helpPopupShow" bgColor="transparent" mode="center">
			<view class="help-popup">
				<view class="flex flex-direction align-center">
					<text class="line-height-24 f-w600 f-s17">紧急救助</text>
					<image src="/static/images/order/help.png" class="width-58 height-58 m-t12" mode=""></image>
				</view>
				<view class="m-t18 text-gray line-height22 f-s12 f-w400">
					<text>当前您的实时位置</text>
				</view>
				<view class="flex p-10 m-t5" style="background: #F5F6F7;border-radius: 16rpx;">
					<image src="/static/images/login/location.png" class="width-20 height-20 shrink-0" mode=""></image>
					<view class="f-s14 f-w600 line-height22 m-l6">
						<text>{{positionInfo.province}}{{positionInfo.city}}{{positionInfo.district}}{{positionInfo.address}}</text>
					</view>
				</view>
				<view v-if="onlineConf.onlineStep == 2" @click="handleStopRecord" hover-class="pressed"
					class="m-t16 text-white f-w500 f-s14 flex justify-center align-center"
					style="height: 80rpx;background: #FE3F59;border-radius: 40rpx;">
					<text>正在录音({{formatSecondsToMinutesSeconds(onlineConf.tipsTime)}})，结束并发送录音</text>
				</view>
				<view v-else @click="handleSendHelp" hover-class="pressed"
					class="m-t16 text-white f-w500 f-s14 flex justify-center align-center"
					style="height: 80rpx;background: #FE3F59;border-radius: 40rpx;">
					<text>发送求助信息</text>
				</view>
				<view class="m-t10 text-theme f-w600 f-s12">
					<text>点击发送求助信息把地理位置发送至平台并开始录音</text>
				</view>
				<view class="help-popup-close" @click="helpPopupShow = false">
					<image src="/static/images/order/close-2.png" class="width-30 height-30" mode=""></image>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import Modal from "@/components/modal/index.vue"
	import {
		detail,
		signUp,
		signUpCancel
	} from "@/api/signup/index.js";
	import {
		callPolice
	} from "@/api/order"
	import toMapAPP from "@/config/toMap.js"
	import dayjs from "dayjs"
	import {
		mapState
	} from 'vuex'
	export default {
		name: "",
		components: {
			Modal
		},
		data() {
			return {
				audio: '', // 录音文件
				recorderManager: null, // 录音管理器
				timer: null, // 录音时间戳
				onlineConf: {
					onlineStep: 1, // 1 开始录音 2录音中 3结束录音 4 播放录音
					isfinish: false, // 是否结束录音
					isRecord: false, // 是否正在录音
					tipsTime: 0, // 录音的时长
				},
				helpPopupShow: false,
				detailData: {},
				queryParams: {
					id: ''
				},
				toastShow: false,
				modalShow: false
			}
		},
		onLoad(query) {
			if (query.id) {
				this.queryParams.id = query.id
				this.getDetail()
			}
		},
		// onPageScroll(event) {
		// 	let scrollTop = event.scrollTop
		// 	// 计算透明度（0-1之间变化）
		// 	// 这里设定当滚动超过100px时完全变为白色，你可以调整这个值
		// 	let navbarOpacity = Math.min(scrollTop / 80, 1)
		// 	this.topBGC = `rgba(255, 255, 255, ${navbarOpacity})`
		// },
		computed: {
			...mapState({
				positionInfo: state => state.user.position || {}
			})
		},
		methods: {
			checkBtnPlaceholder() {
				let status = true
				switch (this.detailData.order_status) {
					case 4:
					case 5:
						status = this.detailData.comment_user_data ? false : true;
						break;
					case 6:
					case 7:
						status = false
						break;
				}
				return status
			},
			// 秒钟格式化分：秒
			formatSecondsToMinutesSeconds(seconds) {
				const mins = Math.floor(seconds / 60);
				const secs = seconds % 60;
			
				// 补零，确保两位数
				const formattedMins = mins.toString().padStart(2, '0');
				const formattedSecs = secs.toString().padStart(2, '0');
			
				return `${formattedMins}:${formattedSecs}`;
			},
			handleStopRecord() {
				// 结束录音
				this.recorderManager.stop()
			},
			// 初始化录音组件
			initOnlibeRecord() {
				this.recorderManager = uni.getRecorderManager();
				let self = this;
				// 监听对象的stop事件
				this.recorderManager.onStop(async (res) => {
					self.onlineConf.onlineStep = 3
					this.resetInterval()
					let params = this.positionInfo
					this.$modal.loading("录音信息正在发送").then(() => {
						callPolice({
							...params,
							audio: res.tempFilePath
						}).then(res => {
							this.$toast("成功发送")
							this.$modal.closeLoading()
						}).catch(() => {
							this.$modal.closeLoading()
						})
					})
				});
				// 监对象的start事件
				this.recorderManager.onStart(function(res) {
					self.onlineConf.onlineStep = 2
					self.getOperateTime();
				});
			},
			// 重置计时
			resetInterval() {
				if (this.timer) {
					this.timer = null
					this.onlineConf.tipsTime = 0
				}
			},
			// 计时
			getOperateTime() {
				this.resetInterval()
				this.timer = setInterval(() => {
					this.onlineConf.tipsTime += 1;
				}, 1000);
			},
			// 开始录音
			async startRecord() {
				let status = await this.getRecordPermission();
				if (status === 1) {
					this.recorderManager.start({
						duration: 1000 * 60 * 5
					})
				}
			},
			// 校验录音权限
			async getRecordPermission() {
				let status = permision.isIOS ? await permision.requestIOS('record') :
					await permision.requestAndroid('android.permission.RECORD_AUDIO');
				if (status === null || status === 1) {
					status = 1;
				} else if (status === 2) {
					// 定位服务未启用
					this.$toast("录音服务未开启")
				} else {
					uni.showModal({
						title: "提示",
						content: '录音权限未开启，请前往设置打开授权',
						confirmText: '前往设置',
						success(res) {
							if (res.confirm) {
								uni.openAppAuthorizeSetting()
							}
						}
					})
				}
				return status
			},
			// 判断值是否为0
			isStrictZero(value) {
				// 排除 null、undefined、false、空字符串
				if (value === null || value === undefined || value === false || value === "") {
					return false;
				}
				return Number(value) !== 0;
			},
			// 发送救助信息
			handleSendHelp() {
				this.startRecord()
				let params = this.positionInfo
				this.$modal.loading("位置信息正在发送").then(() => {
					callPolice(params).then(res => {
						// this.helpPopupShow = false
						this.$toast("成功发送")
						this.$modal.closeLoading()
					}).catch(() => {
						this.$modal.closeLoading()
					})
				})
			
			},
			// 紧急求助按钮
			handleHelp() {
				// 创建录音管理器
				this.initOnlibeRecord()
				this.helpPopupShow = true
			},
			handleOpenMapApp() {
				let {
					lat: latitude,
					lng: longitude,
					address: name
				} = this.detailData
				toMapAPP(latitude, longitude, name)
			},
			// 处理取消报名时间
			handleCancelTime(timestamp) {
				timestamp *= 1000
				// 可取消报名的时间 - 当前时间 = 剩余可取消报名时间
				return dayjs(timestamp).valueOf() - dayjs().valueOf()
			},
			// 检验是否可取消报名
			handleCancelTimeCheck(timestamp) {
				timestamp *= 1000
				// 当前时间是否在可取消时间之后
				return dayjs().isAfter(dayjs(timestamp))
			},
			// 截止报名时间倒计时结束，报名已过期
			handleCutOffTimeFinish() {
				// 修改详情为过期状态
				this.$set(this.detailData, 'status', 3)
			},
			// 处理截止报名时间
			handleCutOffTime(timestamp) {
				timestamp *= 1000
				// 处理错误情况，当前时间在截止时间之后，返回空字符
				if (dayjs().isAfter(dayjs(timestamp))) return ''
				// 截止报名时间 - 当前时间 = 剩余截止倒计时时间
				return dayjs(timestamp).valueOf() - dayjs().valueOf()
			},
			handleConfrimeCancelSignup() {
				this.modalShow = false
				this.$modal.loading('正在取消').then(res => {
					signUpCancel({
						id: this.detailData.id
					}).then(res => {
						this.$modal.closeLoading()
						this.$toast(res.msg)
						uni.$emit('operation', {
							type: 'cancel',
							id: this.detailData.id
						})
					}).catch(() => this.$modal.closeLoading())
				})
			},
			handleSignupCancel() {
				this.modalShow = true
			},
			handleSignup() {
				this.$modal.loading('报名中').then(res => {
					signUp({
						id: this.detailData.id
					}).then(res => {
						this.$modal.closeLoading()
						this.$toast(res.msg)
						this.getDetail()
						uni.$emit('operation', {
							type: 'sign',
							id: this.detailData.id
						})
					}).catch(() => this.$modal.closeLoading())
				})

			},
			// 到达时间格式化
			formatArriveTime(timestamp) {
				return dayjs(timestamp * 1000).format("YYYY年M月D日 H:mm")
			},
			formatTime(minutes) {
				if (minutes < 60) {
					// 如果未超过60分钟，直接显示分钟
					return `${minutes}分钟`;
				} else {
					// 如果超过60分钟，转换为 "时:分" 格式
					const hours = Math.floor(minutes / 60); // 计算小时
					const remainingMinutes = minutes % 60; // 计算剩余的分钟
					return `${hours}小时${remainingMinutes}分钟`;
				}
			},
			getDetail() {
				let {
					lat,
					lng
				} = this.positionInfo
				this.queryParams.lat = lat
				this.queryParams.lng = lng
				detail(this.queryParams).then(res => {
					console.log('res: ', res);
					let {
						data
					} = res
					this.detailData = data
				})
			},
			handleClickVip() {
				this.$toast("VIP客户")
			},
			handleToPage(path) {
				switch (path) {
					default:
						this.$tab.navigateTo(path)
						break;
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	@import '@/common/css/var.scss';

	.container {
		background: url('/static/images/signup/top.png') no-repeat fixed top center / 100% auto;

		.main {

			@include fixed-height;
			@include fixed-bottom;
			overflow: hidden;
			display: flex;
			flex-direction: column;

			.header {
				width: 100%;
				padding: 20rpx 24rpx 0 24rpx;
				box-sizing: border-box;
				// padding-top: var(--status-bar-height);
			}

			.main-content {
				border-radius: 32rpx 32rpx 0rpx 0rpx;
				background-color: #F5F6F7;
				width: 100%;
				padding: 24rpx;
				padding-bottom: 0rpx;
				overflow: hidden;
			}

			.tag {
				overflow: hidden;
				margin-top: 4rpx;

				.tag-item {
					padding: 16rpx 24rpx;
					font-weight: 400;
					font-size: 24rpx;
					color: #202020;
					line-height: 32rpx;
					background: #F0F1F2;
					border-radius: 8rpx;
					float: left;
					margin-right: 20rpx;
					margin-top: 20rpx;
				}
			}


		}
.help-container {
			width: 100rpx;
			height: 100rpx;
			background: rgba(254, 63, 89, .8);
			box-shadow: 0px 4rpx 12rpx 0px #FE3F59;
			border-radius: 50rpx;
			color: #FFFFFF;
			font-size: 24rpx;
			// font-weight: bold;
			touch-action: none;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.help-popup {
			width: 320px;
			background: #FFFFFF;
			border-radius: 10px;
			padding: 40rpx;
			position: relative;

			.help-popup-close {
				margin-top: 32rpx;
				position: absolute;
				top: 100%;
				left: 50%;
				transform: translateX(-50%);
			}
		}
		.disabled {
			background: #B2B8C1;
			pointer-events: none;
		}

		.cancel {
			background: #FE3F59;
			color: #FFFFFF;
		}

		::v-deep .count-down {
			.u-count-down__text {
				font-weight: 400;
				font-size: 22rpx;
				color: #FFFFFF;
				line-height: 32rpx;
			}
		}
	}
</style>